import { Component, OnInit, Input } from '@angular/core';
// 导入表单相关：表单验证、表单构建、表单组
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { CveService } from 'src/app/core/service/cve.service';

@Component({
  selector: 'app-add-relevance',
  templateUrl: './add-relevance.component.html',
  styleUrls: ['./add-relevance.component.scss']
})
export class AddRelevanceComponent implements OnInit {
  @Input() name: string;

  jarName: string;
  artifactName: string;
  version: string;
  data = {};

  relevanceForm: FormGroup;

  constructor(
    private modal: NzModalRef,
    private cveService: CveService,
    private message: NzMessageService,
    fb: FormBuilder
  ) {
    this.relevanceForm = fb.group({
      groupName: [null, Validators.required],
      artifactName: [null, Validators.required],
      version: [null, Validators.required],
    });
  }

  destroyModal(): void {
    this.modal.destroy({ data: 'this the result data' });
  }

  // 执行添加关联组件的方法
  addRelevance(): void {
    console.log(this.relevanceForm.controls);
    console.log('this.name', this.name);
    // tslint:disable-next-line:forin
    for (const c in this.relevanceForm.controls) {
      this.relevanceForm.controls[c].markAsTouched();
    }
    if (this.relevanceForm.valid) {
      this.data = {
        group_name: this.relevanceForm.value.groupName,
        artifact_name: this.relevanceForm.value.artifactName,
        version: this.relevanceForm.value.version,
        jar_name: this.relevanceForm.value.artifactName + '-' + this.relevanceForm.value.version,
        cve_number: this.name,
        modify_time: '2019-03-19 06:03:33'
      };
      this.addService(this.data);
    } else {
      this.message.error('表单校验失败', { nzDuration: 10000 });
    }
  }

  private addService(info: object) {
    this.cveService.addRelevance(info).subscribe((addResult) => {
      // this.result = result;   // 返回的结果
      console.log('==result==', addResult);
      if (addResult.status === 1) {
        this.message.success('添加成功!', {
          nzDuration: 10000
        });
        this.modal.destroy({ data: 'this the result data' });
      } else {
        this.message.error('添加失败!请检查后重新填写', {
          nzDuration: 10000
        });
        this.modal.destroy({ data: 'this the result data' });
      }
    });
  }

  ngOnInit() {
  }

}
